package com.feihong.yw189.bluetooth.startreadcard;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import com.feihong.yw189.bluetooth.bleutils.BleGlobUtils;
import com.feihong.yw189.bluetooth.bleutils.BleHttpUtils;
import com.feihong.yw189.bluetooth.listener.UpLoadListener;
import com.identity.Shell;
import com.identity.globalEnum;

import java.io.IOException;

/**
 * 神思读卡
 * 2017/8/24
 * 张鹏
 */
public class ShenSiConnectUtils {
    private BluetoothDevice remoteDevice;
    private String bleAddress;
    private BluetoothAdapter ba;
    private Context context;
    private Activity mActivity;

    private String name, sex, nation, id_num, address, sign_office, to, from, born;
    private String birth_year, birth_month, birth_day, sign_data, photoHeard;
    private Bitmap photo;
    private String bluetoothName = "";
    private BleHttpUtils bleHttpUtils;
    private Boolean mFlag = false;
    // 注册成功失败监听
    private UpLoadListener mOnUpLoadListener;

    private Shell shell = null;
    private String bleName;
    public ShenSiConnectUtils(Context context, BluetoothAdapter ba, BluetoothDevice remoteDevice,
                              String bleName,    String bleAddress,  final String bluetoothName,
                              Boolean flag, final UpLoadListener mOnUpLoadListener) {
        this.context = context;
        this.mActivity = (Activity) context;
        this.ba = ba;
        this.remoteDevice = remoteDevice;
        this.bleName = bleName;
        this.bleAddress = bleAddress;
        this.mFlag = flag;
        this.bluetoothName = bluetoothName;
        this.mOnUpLoadListener = mOnUpLoadListener;
    }

    public void connect() {
        bleHttpUtils = new BleHttpUtils(context, bluetoothName, mFlag, new UpLoadListener() {
            @Override
            public void onSucUpLoad(String bluetoohName, String address, String sex, String id_num,
                                    String nation, String sign_office, String name, String sign_data,
                                    String birth_year, String birth_month, String birth_day,
                                    Bitmap photo, String filePhoto, String idPath, String to,
                                    String from, String born, String photoHeard) {
                mOnUpLoadListener.onSucUpLoad(bluetoothName, address, sex, id_num, nation,
                        sign_office, name, sign_data, birth_year, birth_month, birth_day,
                        photo, filePhoto, idPath, to,
                        from, born, photoHeard);
                stopConnect();
            }

            @Override
            public void onErrUpLoad(String err) {
                mOnUpLoadListener.onErrUpLoad(err);
                // 读卡失败需要断开连接
                stopConnect();
            }
        });
        try {
            if (shell == null) {
                shell = new Shell(context, remoteDevice);
            }
            shenSiRead();
        } catch (IOException e) {
            mOnUpLoadListener.onErrUpLoad("与机具建立连接失败!");
            e.printStackTrace();
        }
    }

    private void shenSiRead() {
        // 读卡设备
        try {
            globalEnum ge = globalEnum.NONE;
            if (shell == null) {
                try {
                    shell = new Shell(context, remoteDevice);
                } catch (IOException e) {
                    mOnUpLoadListener.onErrUpLoad("与机具建立连接失败!");
                    e.printStackTrace();
                }
            }
            try {
                boolean bRet = false;
                byte[] cardInfo = new byte[256];
                String data;
                ge = shell.Init();
                if (ge == globalEnum.INITIAL_SUCCESS) {
                    bRet = shell.id2ShakeHand();//握手通讯
                    if (bRet) {
                        int nRet = shell.id2ReadCard();
                        if (nRet == 0) {
                            cardInfo = shell.GetCardInfoBytes();
                            String wltPath = "/data/data/" + mActivity.getPackageName() + "/files/";
                            String termBPath = "/mnt/sdcard/";
                            int nret = shell.GetPic(wltPath, termBPath);
                            if (nret > 0) {
                                // 身份证头像
                                photo = BitmapFactory.
                                        decodeFile("/data/data/" + mActivity.getPackageName() + "/files/zp.bmp");
                                photoHeard = BleGlobUtils.replaceBlank(BleGlobUtils.bitmapToBase64(photo));

                                name = shell.GetName(cardInfo).toString().trim();

                                sex = shell.GetGender(cardInfo).toString().trim();

                                nation = shell.GetNational(cardInfo).toString().trim();

                                String birthday = shell.GetBirthday(cardInfo).toString().trim();

                                birth_year = birthday.substring(0, 4);
                                birth_month = birthday.substring(5, 7);
                                birth_day = birthday.substring(8, 10);

                                born = birth_year + birth_month + birth_day;
                                address = shell.GetAddress(cardInfo).toString().trim();

                                id_num = shell.GetIndentityCard(cardInfo).toString().trim();

                                sign_office = shell.GetIssued(cardInfo).toString().trim();

                                from = shell.GetStartDate(cardInfo).toString().trim();

                                to = shell.GetEndDate(cardInfo).toString().trim();

                                String fromYear = from.substring(0, 4);
                                String formMonth = from.substring(5, 7);
                                String fromDay = from.substring(8, 10);

                                if (to.contains("长期")) {
                                    sign_data = fromYear + "." + formMonth + "." + fromDay
                                            + "--" + to.trim();
                                } else {
                                    String toYear = to.substring(0, 4);
                                    String toMonth = to.substring(5, 7);
                                    String toDay = to.substring(8, 10);
                                    sign_data = fromYear + "." + formMonth + "." + fromDay
                                            + "--" + toYear + "." + toMonth + "." + toDay;
                                }
                                Log.e("项目异常", name + "------1------" + id_num);
                                bleHttpUtils.upLoadSfzPhoto(bleName, bleAddress,address, photoHeard, sex, id_num, nation,
                                        sign_office, to, name, from, born, sign_data, birth_year,
                                        birth_month, birth_day,  photo);
                                context.deleteFile("zp.bmp");
                            } else if (nret == -5) {
                                mOnUpLoadListener.onErrUpLoad("照片解码授权文件不正确");
                            } else if (nret == -1) {
                                mOnUpLoadListener.onErrUpLoad("照片原始数据不正确");
                            }
                        } else {
                            mOnUpLoadListener.onErrUpLoad("与设备握手失败,nRet=" + nRet);
                        }
                    } else {
                        mOnUpLoadListener.onErrUpLoad("与设备握手失败,bRet=" + bRet);
                        shell.Destroy();
                    }
                } else {
                    shell.Destroy();
                    mOnUpLoadListener.onErrUpLoad("与机具建立连接失败ge=" + ge);
                }
            } catch (Exception e) {
                mOnUpLoadListener.onErrUpLoad("与机具建立连接失败:" + e.toString());
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
            mOnUpLoadListener.onErrUpLoad("与机具建立连接失败:" + e.toString());
        }
    }

    /**
     * 断开连接
     */
    public void stopConnect() {
//        try {

        try {
            if (shell != null) {
                shell.Destroy();
                shell = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("项目异常", "------断开连接异常------" + e.toString());
            mOnUpLoadListener.onErrUpLoad("");
        }
    }
}
